import { URLSearchParamsInit, useSearchParams } from 'react-router-dom'

interface IMap {
  [key: string]: string
}

export default () => {
  const Url = {
    hash: {} as IMap,
    search: {} as IMap,
  } as {
    hash: IMap
    search: IMap
    [key: string]: IMap
  }

  window.location.hash
    .slice(1)
    .split('&')
    .map((str) => {
      const kv = str.split('=')
      Url.hash[kv[0]] = kv[1]
    })

  if (window.location.hash.indexOf('?') != -1) {
    let str = window.location.hash.substr(window.location.hash.indexOf('?') + 1)
    str.split('&').map((str) => {
      const kv = str.split('=')
      Url.search[kv[0]] = kv[1]
    })
  }

  // window.location.hash
  //   .slice(1)
  //   .split('&')
  //   .map((str) => {
  //     const kv = str.split('=')
  //     Url.search[kv[0]] = kv[1]
  //   })
  return Url
}

// unknown 只能赋值给 any 和 unknown，unknown 类型上不能读取方法
const isFalsy = (value: unknown) => (value === 0 ? false : !value)

// 在一个函数里改变传入的对象是不好的，因为对象是引用类型，这里改变了，其他地方也要改变
export function clearObject(object: { [key: string]: unknown }) {
  const result = { ...object }

  Object.keys(result).forEach((key) => {
    const value = result[key]

    if (isFalsy(value)) {
      delete result[key]
    }
  })

  return result
}

export const useAddUrlSearchParam = () => {
  const [searchParams] = useSearchParams()
  return (params: { [key in string]: unknown }) => {
    const o = clearObject({
      ...Object.fromEntries(searchParams),
      ...params,
    }) as URLSearchParamsInit
    return o
  }
}

export const useAppendUrlParam = () => {
  const [searchParams] = useSearchParams()
  return (url: string, key: string = 'instance') => {
    const v = searchParams.get(key)
    if (v == null) return url
    if (url.indexOf('?') !== -1) {
      url = url + '&' + key + '=' + v
    } else {
      url = url + '?' + key + '=' + v
    }
    return url
  }
}
